package com.yungongyu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    // 创建工厂，建造者模式
    private  static SqlSessionFactory factory = null;

    static {  // 通过静态代码块，唯一一次创建SqlSessionFactory实例
        try {
            //创建Mybatis 全局配置文件
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            // 链接数据库
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    // 创建并返回SqlSession实例
    public static SqlSession createSqlSession(){
        // 关闭自动提交事务
        return factory.openSession(false);
    }

    // 关闭SqlSession
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession != null){
            sqlSession.close();
        }

    }


}
